package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/course")
@Scope("prototype")
public class CourseController extends BaseController{

    @Autowired
    ICourseService iCourseService;

    @GetMapping()
    public Result findAll(@RequestParam Map reMap,
                          @RequestParam(value = "schoolIdList",defaultValue = "") String[] schoolIdList,
                          @RequestParam(value = "subjectsIdList",defaultValue = "") String[] subjectsIdList,
                          @RequestParam(value = "quarterNumList",defaultValue = "") String[] quarterNumList,
                          @RequestParam(value = "statusList",defaultValue = "") String[] statusList,
                          @RequestParam(value = "yearClassIdList",defaultValue = "") String[] yearClassIdList,
                          @RequestParam(value = "lessonType",defaultValue = "") String lessonType){
            Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
            Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 10: Integer.valueOf((String)reMap.get("pageSize"));

            Map<String,Object> searchMap = new HashMap<>();
            Page<Course> page = new Page<>(pageNum,pageSize);

            String name = (String) reMap.get("name");//名称

            QueryWrapper<Course> queryWrapper =  new QueryWrapper<>();
            //queryWrapper.apply("1=1");
            //queryWrapper.apply("FIND_IN_SET("+school_id+",school_ids)");
            queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
            queryWrapper.in(statusList.length>0,"status",statusList);
            queryWrapper.in(subjectsIdList.length>0,"subjects_id",subjectsIdList);
            queryWrapper.eq(StringUtils.isNotBlank(lessonType),"lesson_type",lessonType);
            queryWrapper.eq("deleted",0);

            //queryWrapper.and();

            if(schoolIdList.length>0){
                //queryWrapper.apply("isAppoitSchool("+school_id+")");
                //queryWrapper.in("id","select for_id from appoint_school where school_id="+school_id);
                String schoolIdStr = String.join(",",schoolIdList);
                queryWrapper.and(i->i.inSql("id","select for_id from appoint_school where type=1 and school_id in("+schoolIdStr+")").or().eq("opening_school_type",1));
            }else {
                //queryWrapper.in("id","select for_id from appoint_school where school_id in("+baseSchoolIdStr+")");
                queryWrapper.and(i->i.inSql("id","select for_id from appoint_school where type=1 and school_id in("+baseSchoolIdStr+")").or().eq("opening_school_type",1));

            }

            if(yearClassIdList.length>0){
                queryWrapper.in("year_class_id",yearClassIdList);
            }

            if(quarterNumList.length>0){
                queryWrapper.in("quarter_num",quarterNumList);
            }


            queryWrapper.orderByDesc("created_at");

            IPage<Course> iPage = iCourseService.findAll(page,queryWrapper);

            //分页查询
            /*Page<Course> employees = employeeMapper.selectPage(new Page<>(3, 2), null);
            System.out.println("数据为："+employees.getRecords());
            System.out.println("总数为："+employees.getTotal()+",总页数为："+employees.getPages());
            System.out.println("当前页为："+employees.getCurrent()+",每页限制："+employees.getSize());*/

            return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    //@RequiresPermissions(value = "course:findbyid")
    @GetMapping(value = "/{id}",name = "course:findbyid")
    public Result findById(@PathVariable(value = "id") Long id){
            //System.out.print("findById");
            Course course = iCourseService.findOne(id);
            return new Result(Code.OK,course);
    }

    @PostMapping()
    @RepeatSubmit(expireSeconds = 30)
    public Result save(@RequestBody Course course){
            iCourseService.saveTo(course);
            //System.out.println(course);
            return new Result(Code.OK);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Course course){

            iCourseService.updateTo(course,this.baseSchoolIdList);
            return new Result(Code.OK);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
            System.out.print("id:"+id);
            boolean rs =  iCourseService.deleteForId(id);
            return new Result(rs?Code.OK:Code.ERROR);
    }

    @PutMapping("/statusToggle/{id}/{status}")
    public Result statusToggle(@PathVariable(value = "id") Long id,@PathVariable(value = "status") Integer status){
        //修改
        boolean rs = iCourseService.update(null,new LambdaUpdateWrapper<Course>().eq(Course::getId,id).set(Course::getStatus,status));
        return new Result(rs?Code.OK:Code.ERROR);
    }
}
